package com.marketapp.validators;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.marketapp.domain.UserInfo;
import com.marketapp.helper.ServiceException;
import com.marketapp.service.IUserService;
import com.marketapp.util.StringUtil;

@Component
public class UserInfoValidator implements Validator{
	
	@Autowired
	IUserService userService;
	
	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return UserInfo.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,"userName","username.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,"userPassword","password.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,"userDetails.firstName","firstname.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,"userDetails.lastName","lastName.required");
		UserInfo userInfo = (UserInfo) target;
		try {
			if(userService.checkifUserExists(StringUtil.getStringUpperCase(userInfo.getUserName()))){
				errors.reject("username.exists");
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		
		
	}

}
